package com.atguigu.springcloud.controller.lb;

import org.springframework.cloud.client.ServiceInstance;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @USER: dayu
 * @DATE: 2020/3/25
 * @DESCRIPTION: 手写负载均衡算法
 */
@Component
public class MyLoadBalanceImpl implements ILoadBalance {
    private AtomicInteger ai = new AtomicInteger(0);

    /**
     * @param modulo
     * @return
     */
    private int incrementAndGetModulo(int modulo) {
        int current;
        int next;
        do {
            current = this.ai.get();
//            next = (current + 1) % modulo;
            next = current > Integer.MAX_VALUE ? 1 : current + 1;
        } while (!this.ai.compareAndSet(current, next));
        int index = next % modulo;
        System.out.println("======第几次访问，次数====" + next + ",下标是：" + index);
        return index;
    }

    @Override
    public ServiceInstance instances(List<ServiceInstance> serviceInstances) {
        int next = incrementAndGetModulo(serviceInstances.size());
        return serviceInstances.get(next);
    }
}
